package thread;

//线程池

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class Test4_pool {
    public static void main(String[] args) {
        //线程池核心线程数
        int corePoolSize = 3;
        //线程池最大线程数
        int maxiPoolSize = 5;
        //最大空闲时间，超过则销毁线程
        long keepAliveTime = 10;
        //枚举 时间单位
        TimeUnit unit = TimeUnit.SECONDS;
        //有界阻塞列 容量为2
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(2);
        //线程创建工厂
        ThreadFactory threadFactory = new NameThreadFactory();
        //线程池拒绝策略
        RejectedExecutionHandler handler = new MyIgnorePolicy();
        //线程池 通常使用执行器
        ThreadPoolExecutor executor = null;
        try {
            //推荐的创建线程池方法（不推荐使用现成的API创建线程池）：
            executor = new ThreadPoolExecutor(corePoolSize,maxiPoolSize,keepAliveTime,unit,workQueue,threadFactory,handler);
            //预启动核心线程 提升效率
            executor.prestartAllCoreThreads();
            //执行任务
            //任务数
            int count = 10;
            for (int i =0;i<count;i++){
                Task task = new Task(String.valueOf(i));
                executor.submit(task);//线程池中最多同时执行5个任务+2个队列 提交任务到线程池  还有3个任务无法执行
            }
        }finally {
            assert executor != null;  //断言，可开关，-ea -da
            executor.shutdown();
        }
    }

    //任务类
    static class Task implements Runnable{
        private String name;
        public Task(String name){
            this.name = name;
        }
        @Override
        public void run() {
            try {
                System.out.println(this.toString()+"is running");
                Thread.sleep(3000);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }

        @Override
        public String toString() {
            return "RunnableTask [name="+name+"]";
        }
    }
    static class NameThreadFactory implements ThreadFactory{
        //线程id AtomicInteger 原子整型类
        private final AtomicInteger threadId = new AtomicInteger(1);
        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r,"线程-"+threadId.getAndIncrement());
            System.out.println(t.getName()+"已经创建");
            return t;
        }
    }

    //线程池拒绝策略
    public static class MyIgnorePolicy implements RejectedExecutionHandler{

        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            doLog(r,executor);
        }
        private void doLog(Runnable r, ThreadPoolExecutor executor){
            //做日志记录
            System.err.println("线程池:"+executor.toString()+r.toString()+"被拒绝");
        }
    }
}
